﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace OpenESSOConfigurator.BusinessLayer.Serializer
{
    public class AtomsSerializer<T>
    {
        private T _t;
        private XmlSerializer _serializer;

        public T Generic
        {
            get { return _t; }
            set { _t = value; }
        }

        public XmlSerializer Serializer
        {
            get { return _serializer; }
            set { _serializer = value; }
        }

        public AtomsSerializer()
        {
            Serializer = new XmlSerializer(typeof(T));
            Serializer.UnknownNode += new XmlNodeEventHandler(Serializer_UnknownNode);
            Serializer.UnknownAttribute += new XmlAttributeEventHandler(Serializer_UnknownAttribute);
        }

        public StringWriter AtomSerializer()
        {
            StringWriter strWriter = new StringWriter();
            try
            {
                Serializer.Serialize(strWriter, Generic);
                strWriter.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return strWriter;
        }

        public void AtomDeserializer(StringReader strReader)
        {
            try
            {
                Generic = (T)Serializer.Deserialize(strReader);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        protected void Serializer_UnknownNode(object sender, XmlNodeEventArgs e)
        {
            Console.WriteLine("Unknown Node:" + e.Name + "\t" + e.Text);
        }

        protected void Serializer_UnknownAttribute(object sender, XmlAttributeEventArgs e)
        {
            System.Xml.XmlAttribute attr = e.Attr;
            Console.WriteLine("Unknown attribute " +
            attr.Name + "='" + attr.Value + "'");
        }
    }
}
